package com.af.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import java.util.Locale;

/**
 * @author : zhenyun.su
 * @comment : 获取多语言
 * 使用说明： 注册为Bean
 *     @Autowired
 *     private MessageSource messageSource;
 *     @Bean
 *     public SzyI18nService szyI18nService(){
 *         return new SzyI18nService(messageSource);
 *     }
 *  来源： 3-webmvc/1-restful
 * @since : 2019/6/27
 */

public class AfI18nService {
    private static final Logger logger = LoggerFactory.getLogger(AfI18nService.class);

    private MessageSource messageSource;

    public AfI18nService(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    /**
     * @comment :  获取多语言值, 不抛出异常
     * @params  :  key=Welcome {0} System, param=占位符值； lang =zh-CN|en-US
     * @return  :  成功返回对应资源，失败返回key
     */
    public String getI18n(String key, @Nullable Object[] param, String lang) {
        try {
            Locale locale = Locale.getDefault();
            if (!StringUtils.isEmpty(lang)) {
                locale = Locale.forLanguageTag(lang);
            }
            return getMessage(key, param, locale);
        } catch (Exception e) {
            logger.error("getMsg, exception: {}", e.getMessage());
            return key;
        }
    }

    /**
     * @comment :  获取多语言值, 不抛出异常
     */
    public String getI18n(String key, @Nullable Object[] param, Locale locale) {
        try {
            return getMessage(key, param, locale);
        } catch (Exception e) {
            logger.error("getMsg, exception: {}", e.getMessage());
            return key;
        }
    }

    public String getI18nError(String key, @Nullable Object[] param,  Locale locale) {
        try {
            return getMessage(key, param, locale);
        } catch (Exception e) {
            logger.error("{} get I18n value exception: {}", key, e.getMessage());
            return "";
        }
    }

    public String getMessage(String key, Locale locale) throws NoSuchMessageException {
        return messageSource.getMessage(key, null, locale);
    }

    public String getMessage(String key, @Nullable Object[] param, Locale locale) throws NoSuchMessageException {
        return messageSource.getMessage(key, param, locale);
    }

    public String getMessage(String key, @Nullable Object[] param, @Nullable String var3, Locale locale) {
        return messageSource.getMessage(key, param, var3, locale);
    }

}
